package com.hcx.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hcx.reggie.dto.DishDto;
import com.hcx.reggie.exception.CustomException;
import com.hcx.reggie.pojo.Category;
import com.hcx.reggie.pojo.Dish;
import com.hcx.reggie.pojo.DishFlavor;
import com.hcx.reggie.service.CategoryService;
import com.hcx.reggie.service.DishFlavorService;
import com.hcx.reggie.service.DishService;
import com.hcx.reggie.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@RestController
@CrossOrigin
@RequestMapping("dish")
public class DishController {


    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 获取菜品页面
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R<Page<DishDto>> page(int page,int pageSize,String name){
        Page<Dish> Ipage = new Page(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        if(name != null) {
            wrapper.like(Dish::getName, name);
        }
        wrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(Ipage, wrapper);
        BeanUtils.copyProperties(Ipage,dishDtoPage,"records");
        List<Dish> records = Ipage.getRecords();
        List<DishDto> list = records.stream().map((dish)->{
            Long categoryId = dish.getCategoryId();
            Category cateById = categoryService.getById(categoryId);
            String cateByIdName = cateById.getName();
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            dishDto.setCategoryName(cateByIdName);
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 添加菜品
     * @param dishDto
     * @return
     */
    @PostMapping()
    public R<String> add(@RequestBody DishDto dishDto){
        boolean save = dishService.saveWithFlavor(dishDto);
        if (save){
            return R.success("菜品添加成功");
        }
        return R.error("菜品添加失败");
    }
    @PutMapping()
    public R<String> update(@RequestBody DishDto dishDto){

        dishService.updateWithFlavor(dishDto);

        return R.success("更新成功");
    }

    /**
     * 根据菜品的id查询菜品的信息
     */
    @GetMapping("{id}")
    public R<DishDto> updatePage(@PathVariable Long id){
        log.info("{}",id);
        DishDto byId = dishService.getByIdWithFlavor(id);
        return R.success(byId);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */

    @Transactional
    @DeleteMapping()
    public R<String> removeBatch(@RequestParam List<Long> ids){
        log.info("{}",ids);
        for (Long id : ids) {
            Dish byId = dishService.getById(id);
            if(byId.getStatus() == 1){
                throw new CustomException("停售后才可以删除");
            }
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
            dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        }

        dishService.removeBatchByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 批量修改状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("status/{status}")
    public R<String> statusBatch(@PathVariable int status,@RequestParam List<Long> ids){
//        List<Dish> dishes = dishService.listByIds(ids);
//        for (Dish dish : dishes) {
//            Dish byId = dishService.getById(dish.getId());
//            Integer statusDish = byId.getStatus();
//            if(statusDish == status){
//                return R.error(dish.getName()+"已经起售了");
//            }
//        }
        for (Long id : ids) {
            LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(Dish::getId,id);
            Dish dish = new DishDto();
            dish.setStatus(status);
            dishService.update(dish,dishLambdaQueryWrapper);
        }

        return R.success("");
    }

    /**
     * 套餐菜品回显
     * @param categoryId
     * @return
     */
    @GetMapping("list")
    public R<List<DishDto>> list(Long categoryId) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (categoryId != null) {
            dishLambdaQueryWrapper.eq(Dish::getCategoryId, categoryId);
        }
        dishLambdaQueryWrapper.eq(Dish::getStatus, 1);//查询起售状态的菜品
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        List<DishDto> dishDtoList = list.stream().map((dish) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }
}
